

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>8.11. weakref — Weak references &mdash; Python v2.7.8 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7.8',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7.8 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7.8 documentation" href="../index.html" />
    <link rel="up" title="8. Data Types" href="datatypes.html" />
    <link rel="next" title="8.12. UserDict — Class wrapper for dictionary objects" href="userdict.html" />
    <link rel="prev" title="8.10. Queue — A synchronized queue class" href="queue.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" accesskey="U">8. Data Types</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-weakref">
<span id="weakref-weak-references"></span><h1>8.11. <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> &#8212; Weak references<a class="headerlink" href="#module-weakref" title="Permalink to this headline">¶</a></h1>
<p class="versionadded">
<span class="versionmodified">New in version 2.1.</span></p>
<p><strong>Source code:</strong> <a class="reference external" href="http://hg.python.org/cpython/file/2.7/Lib/weakref.py">Lib/weakref.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> module allows the Python programmer to create <em class="dfn">weak
references</em> to objects.</p>
<p>In the following, the term <em class="dfn">referent</em> means the object which is referred to
by a weak reference.</p>
<p>A weak reference to an object is not enough to keep the object alive: when the
only remaining references to a referent are weak references,
<a class="reference internal" href="../glossary.html#term-garbage-collection"><em class="xref std std-term">garbage collection</em></a> is free to destroy the referent and reuse its memory
for something else.  A primary use for weak references is to implement caches or
mappings holding large objects, where it&#8217;s desired that a large object not be
kept alive solely because it appears in a cache or mapping.</p>
<p>For example, if you have a number of large binary image objects, you may wish to
associate a name with each.  If you used a Python dictionary to map names to
images, or images to names, the image objects would remain alive just because
they appeared as values or keys in the dictionaries.  The
<a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> classes supplied by
the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> module are an alternative, using weak references to construct
mappings that don&#8217;t keep objects alive solely because they appear in the mapping
objects.  If, for example, an image object is a value in a
<a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a>, then when the last remaining references to that
image object are the weak references held by weak mappings, garbage collection
can reclaim the object, and its corresponding entries in weak mappings are
simply deleted.</p>
<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> use weak references
in their implementation, setting up callback functions on the weak references
that notify the weak dictionaries when a key or value has been reclaimed by
garbage collection.  Most programs should find that using one of these weak
dictionary types is all they need &#8211; it&#8217;s not usually necessary to create your
own weak references directly.  The low-level machinery used by the weak
dictionary implementations is exposed by the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> module for the
benefit of advanced uses.</p>
<p>Not all objects can be weakly referenced; those objects which can include class
instances, functions written in Python (but not in C), methods (both bound and
unbound), sets, frozensets, file objects, <a class="reference internal" href="../glossary.html#term-generator"><em class="xref std std-term">generator</em></a>s, type objects,
<tt class="xref py py-class docutils literal"><span class="pre">DBcursor</span></tt> objects from the <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><tt class="xref py py-mod docutils literal"><span class="pre">bsddb</span></tt></a> module, sockets, arrays, deques,
regular expression pattern objects, and code objects.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.4: </span>Added support for files, sockets, arrays, and patterns.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.7: </span>Added support for thread.lock, threading.Lock, and code objects.</p>
<p>Several built-in types such as <a class="reference internal" href="functions.html#list" title="list"><tt class="xref py py-class docutils literal"><span class="pre">list</span></tt></a> and <a class="reference internal" href="stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> do not directly
support weak references but can add support through subclassing:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Dict</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="n">obj</span> <span class="o">=</span> <span class="n">Dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>   <span class="c"># this object is weak referenceable</span>
</pre></div>
</div>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Other built-in types such as <a class="reference internal" href="functions.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a> and <a class="reference internal" href="functions.html#long" title="long"><tt class="xref py py-class docutils literal"><span class="pre">long</span></tt></a> do not support
weak references even when subclassed.</p>
</div>
<p>Extension types can easily be made to support weak references; see
<a class="reference internal" href="../extending/newtypes.html#weakref-support"><em>Weak Reference Support</em></a>.</p>
<dl class="class">
<dt id="weakref.ref">
<em class="property">class </em><tt class="descclassname">weakref.</tt><tt class="descname">ref</tt><big>(</big><em>object</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#weakref.ref" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a weak reference to <em>object</em>.  The original object can be retrieved by
calling the reference object if the referent is still alive; if the referent is
no longer alive, calling the reference object will cause <a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a> to be
returned.  If <em>callback</em> is provided and not <a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a>, and the returned
weakref object is still alive, the callback will be called when the object is
about to be finalized; the weak reference object will be passed as the only
parameter to the callback; the referent will no longer be available.</p>
<p>It is allowable for many weak references to be constructed for the same object.
Callbacks registered for each weak reference will be called from the most
recently registered callback to the oldest registered callback.</p>
<p>Exceptions raised by the callback will be noted on the standard error output,
but cannot be propagated; they are handled in exactly the same way as exceptions
raised from an object&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method.</p>
<p>Weak references are <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> if the <em>object</em> is hashable.  They will maintain
their hash value even after the <em>object</em> was deleted.  If <a class="reference internal" href="functions.html#hash" title="hash"><tt class="xref py py-func docutils literal"><span class="pre">hash()</span></tt></a> is called
the first time only after the <em>object</em> was deleted, the call will raise
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>.</p>
<p>Weak references support tests for equality, but not ordering.  If the referents
are still alive, two references have the same equality relationship as their
referents (regardless of the <em>callback</em>).  If either referent has been deleted,
the references are equal only if the reference objects are the same object.</p>
<p class="versionchanged">
<span class="versionmodified">Changed in version 2.4: </span>This is now a subclassable type rather than a factory function; it derives from
<a class="reference internal" href="functions.html#object" title="object"><tt class="xref py py-class docutils literal"><span class="pre">object</span></tt></a>.</p>
</dd></dl>

<dl class="function">
<dt id="weakref.proxy">
<tt class="descclassname">weakref.</tt><tt class="descname">proxy</tt><big>(</big><em>object</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#weakref.proxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a proxy to <em>object</em> which uses a weak reference.  This supports use of
the proxy in most contexts instead of requiring the explicit dereferencing used
with weak reference objects.  The returned object will have a type of either
<tt class="docutils literal"><span class="pre">ProxyType</span></tt> or <tt class="docutils literal"><span class="pre">CallableProxyType</span></tt>, depending on whether <em>object</em> is
callable.  Proxy objects are not <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> regardless of the referent; this
avoids a number of problems related to their fundamentally mutable nature, and
prevent their use as dictionary keys.  <em>callback</em> is the same as the parameter
of the same name to the <a class="reference internal" href="#weakref.ref" title="weakref.ref"><tt class="xref py py-func docutils literal"><span class="pre">ref()</span></tt></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="weakref.getweakrefcount">
<tt class="descclassname">weakref.</tt><tt class="descname">getweakrefcount</tt><big>(</big><em>object</em><big>)</big><a class="headerlink" href="#weakref.getweakrefcount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of weak references and proxies which refer to <em>object</em>.</p>
</dd></dl>

<dl class="function">
<dt id="weakref.getweakrefs">
<tt class="descclassname">weakref.</tt><tt class="descname">getweakrefs</tt><big>(</big><em>object</em><big>)</big><a class="headerlink" href="#weakref.getweakrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all weak reference and proxy objects which refer to <em>object</em>.</p>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakKeyDictionary">
<em class="property">class </em><tt class="descclassname">weakref.</tt><tt class="descname">WeakKeyDictionary</tt><big>(</big><span class="optional">[</span><em>dict</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#weakref.WeakKeyDictionary" title="Permalink to this definition">¶</a></dt>
<dd><p>Mapping class that references keys weakly.  Entries in the dictionary will be
discarded when there is no longer a strong reference to the key.  This can be
used to associate additional data with an object owned by other parts of an
application without adding attributes to those objects.  This can be especially
useful with objects that override attribute accesses.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Caution: Because a <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> is built on top of a Python
dictionary, it must not change size when iterating over it.  This can be
difficult to ensure for a <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> because actions
performed by the program during iteration may cause items in the
dictionary to vanish &#8220;by magic&#8221; (as a side effect of garbage collection).</p>
</div>
</dd></dl>

<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> objects have the following additional methods.  These
expose the internal references directly.  The references are not guaranteed to
be &#8220;live&#8221; at the time they are used, so the result of calling the references
needs to be checked before being used.  This can be used to avoid creating
references that will cause the garbage collector to keep the keys around longer
than needed.</p>
<dl class="method">
<dt id="weakref.WeakKeyDictionary.iterkeyrefs">
<tt class="descclassname">WeakKeyDictionary.</tt><tt class="descname">iterkeyrefs</tt><big>(</big><big>)</big><a class="headerlink" href="#weakref.WeakKeyDictionary.iterkeyrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterable of the weak references to the keys.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="method">
<dt id="weakref.WeakKeyDictionary.keyrefs">
<tt class="descclassname">WeakKeyDictionary.</tt><tt class="descname">keyrefs</tt><big>(</big><big>)</big><a class="headerlink" href="#weakref.WeakKeyDictionary.keyrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of weak references to the keys.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakValueDictionary">
<em class="property">class </em><tt class="descclassname">weakref.</tt><tt class="descname">WeakValueDictionary</tt><big>(</big><span class="optional">[</span><em>dict</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#weakref.WeakValueDictionary" title="Permalink to this definition">¶</a></dt>
<dd><p>Mapping class that references values weakly.  Entries in the dictionary will be
discarded when no strong reference to the value exists any more.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Caution:  Because a <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> is built on top of a Python
dictionary, it must not change size when iterating over it.  This can be
difficult to ensure for a <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> because actions performed
by the program during iteration may cause items in the dictionary to vanish &#8220;by
magic&#8221; (as a side effect of garbage collection).</p>
</div>
</dd></dl>

<p><a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> objects have the following additional methods.
These method have the same issues as the <tt class="xref py py-meth docutils literal"><span class="pre">iterkeyrefs()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">keyrefs()</span></tt>
methods of <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt></a> objects.</p>
<dl class="method">
<dt id="weakref.WeakValueDictionary.itervaluerefs">
<tt class="descclassname">WeakValueDictionary.</tt><tt class="descname">itervaluerefs</tt><big>(</big><big>)</big><a class="headerlink" href="#weakref.WeakValueDictionary.itervaluerefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterable of the weak references to the values.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="method">
<dt id="weakref.WeakValueDictionary.valuerefs">
<tt class="descclassname">WeakValueDictionary.</tt><tt class="descname">valuerefs</tt><big>(</big><big>)</big><a class="headerlink" href="#weakref.WeakValueDictionary.valuerefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of weak references to the values.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakSet">
<em class="property">class </em><tt class="descclassname">weakref.</tt><tt class="descname">WeakSet</tt><big>(</big><span class="optional">[</span><em>elements</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#weakref.WeakSet" title="Permalink to this definition">¶</a></dt>
<dd><p>Set class that keeps weak references to its elements.  An element will be
discarded when no strong reference to it exists any more.</p>
<p class="versionadded">
<span class="versionmodified">New in version 2.7.</span></p>
</dd></dl>

<dl class="data">
<dt id="weakref.ReferenceType">
<tt class="descclassname">weakref.</tt><tt class="descname">ReferenceType</tt><a class="headerlink" href="#weakref.ReferenceType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for weak references objects.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.ProxyType">
<tt class="descclassname">weakref.</tt><tt class="descname">ProxyType</tt><a class="headerlink" href="#weakref.ProxyType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for proxies of objects which are not callable.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.CallableProxyType">
<tt class="descclassname">weakref.</tt><tt class="descname">CallableProxyType</tt><a class="headerlink" href="#weakref.CallableProxyType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for proxies of callable objects.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.ProxyTypes">
<tt class="descclassname">weakref.</tt><tt class="descname">ProxyTypes</tt><a class="headerlink" href="#weakref.ProxyTypes" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence containing all the type objects for proxies.  This can make it simpler
to test if an object is a proxy without being dependent on naming both proxy
types.</p>
</dd></dl>

<dl class="exception">
<dt id="weakref.ReferenceError">
<em class="property">exception </em><tt class="descclassname">weakref.</tt><tt class="descname">ReferenceError</tt><a class="headerlink" href="#weakref.ReferenceError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a proxy object is used but the underlying object has been
collected.  This is the same as the standard <a class="reference internal" href="#weakref.ReferenceError" title="weakref.ReferenceError"><tt class="xref py py-exc docutils literal"><span class="pre">ReferenceError</span></tt></a> exception.</p>
</dd></dl>

<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0205"><strong>PEP 0205</strong></a> - Weak References</dt>
<dd>The proposal and rationale for this feature, including links to earlier
implementations and information about similar features in other languages.</dd>
</dl>
</div>
<div class="section" id="weak-reference-objects">
<span id="weakref-objects"></span><h2>8.11.1. Weak Reference Objects<a class="headerlink" href="#weak-reference-objects" title="Permalink to this headline">¶</a></h2>
<p>Weak reference objects have no attributes or methods, but do allow the referent
to be obtained, if it still exists, by calling it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">weakref</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Object</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o2</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="ow">is</span> <span class="n">o2</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If the referent no longer exists, calling the reference object returns
<a class="reference internal" href="constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">o</span><span class="p">,</span> <span class="n">o2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">r</span><span class="p">()</span>
<span class="go">None</span>
</pre></div>
</div>
<p>Testing that a weak reference object is still live should be done using the
expression <tt class="docutils literal"><span class="pre">ref()</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">None</span></tt>.  Normally, application code that needs to use
a reference object should follow this pattern:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># r is a weak reference object</span>
<span class="n">o</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>
<span class="k">if</span> <span class="n">o</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
    <span class="c"># referent has been garbage collected</span>
    <span class="k">print</span> <span class="s">&quot;Object has been deallocated; can&#39;t frobnicate.&quot;</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&quot;Object is still live!&quot;</span>
    <span class="n">o</span><span class="o">.</span><span class="n">do_something_useful</span><span class="p">()</span>
</pre></div>
</div>
<p>Using a separate test for &#8220;liveness&#8221; creates race conditions in threaded
applications; another thread can cause a weak reference to become invalidated
before the weak reference is called; the idiom shown above is safe in threaded
applications as well as single-threaded applications.</p>
<p>Specialized versions of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><tt class="xref py py-class docutils literal"><span class="pre">ref</span></tt></a> objects can be created through subclassing.
This is used in the implementation of the <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt></a> to reduce
the memory overhead for each entry in the mapping.  This may be most useful to
associate additional information with a reference, but could also be used to
insert additional processing on calls to retrieve the referent.</p>
<p>This example shows how a subclass of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><tt class="xref py py-class docutils literal"><span class="pre">ref</span></tt></a> can be used to store
additional information about an object and affect the value that&#8217;s returned when
the referent is accessed:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">weakref</span>

<span class="k">class</span> <span class="nc">ExtendedRef</span><span class="p">(</span><span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="o">**</span><span class="n">annotations</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">ExtendedRef</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">annotations</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Return a pair containing the referent and the number of</span>
<span class="sd">        times the reference has been called.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">ob</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">ExtendedRef</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__call__</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">ob</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">ob</span> <span class="o">=</span> <span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">ob</span>
</pre></div>
</div>
</div>
<div class="section" id="example">
<span id="weakref-example"></span><h2>8.11.2. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>This simple example shows how an application can use objects IDs to retrieve
objects that it has seen before.  The IDs of the objects can then be used in
other data structures without forcing the objects to remain alive, but the
objects can still be retrieved by ID if they do.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">weakref</span>

<span class="n">_id2obj_dict</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">remember</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="n">oid</span> <span class="o">=</span> <span class="nb">id</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span> <span class="o">=</span> <span class="n">obj</span>
    <span class="k">return</span> <span class="n">oid</span>

<span class="k">def</span> <span class="nf">id2obj</span><span class="p">(</span><span class="n">oid</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.11. <tt class="docutils literal"><span class="pre">weakref</span></tt> &#8212; Weak references</a><ul>
<li><a class="reference internal" href="#weak-reference-objects">8.11.1. Weak Reference Objects</a></li>
<li><a class="reference internal" href="#example">8.11.2. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="queue.html"
                        title="previous chapter">8.10. <tt class="docutils literal docutils literal docutils literal"><span class="pre">Queue</span></tt> &#8212; A synchronized queue class</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="userdict.html"
                        title="next chapter">8.12. <tt class="docutils literal docutils literal docutils literal"><span class="pre">UserDict</span></tt> &#8212; Class wrapper for dictionary objects</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/weakref.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             >next</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" >8. Data Types</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2014, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jun 29, 2014.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>